package cn.chenhuanming.shh.administer.repository;

import cn.chenhuanming.shh.administer.entity.jpa.EstateBroker;
import cn.chenhuanming.shh.administer.entity.jpa.projection.EstateBrokerAllInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.security.access.prepost.PreAuthorize;

import java.util.List;

/**
 * Generated by Spring Data Generator on 25/07/2017
 */
@RepositoryRestResource(excerptProjection = EstateBrokerAllInfo.class)
public interface EstateBrokerRepository extends JpaRepository<EstateBroker, Integer> {

    /**
     * 通过经纪人id和楼盘id查找他们的关系表
     *
     * @param brokerId
     * @param estateId
     * @return
     */
    @Query(value = "SELECT eb FROM EstateBroker AS eb " +
            "WHERE eb.userBroker.id=:brokerId AND eb.estate.id=:estateId")
    EstateBroker findByBrokerIdAndEstateId(@Param("brokerId") String brokerId, @Param("estateId") String estateId);

    @PreAuthorize("hasAnyRole('ROLE_SHOP_BROKER')")
    @Query(value = "SELECT eb FROM EstateBroker eb WHERE eb.userBroker.username = ?#{principal.username} AND eb.estate.name like %:estateName%")
    List<EstateBroker> findMyEstates(@Param("estateName") String estateName);
}
